/**
 * @Author yinyunqi
 * @date 2017年12月22日
 * @Content 处理家庭信息
 */
package com.yongqi.controller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.yongqi.model.Family;
import com.yongqi.pub.EmailHelper;
import com.yongqi.pub.PrincipalFormat;
import com.yongqi.service.FamilyService;

@RequestMapping("/family") // 处理 /family 请求
@Controller // 声明控制器
public class FamilyController {
	@Autowired
	FamilyService familyService;
	
	Logger log = LoggerFactory.getLogger(FamilyController.class);
	
	@ResponseBody // 返回JSON字符串，不需要找页面
	@RequestMapping("/insert") // 处理 /family/insert 请求
	public String insertTest() {
		familyService.insertFamily();
		return "insert success";
	}

	// 注册家庭
	@ResponseBody
	@RequestMapping("/register")
	public String registerFamily(HttpServletRequest request) throws SQLException {
		String familyaccount = request.getParameter("familyaccount");
		String familyname = request.getParameter("familyname");
		String familypassword = request.getParameter("familypassword");
		String familyemail = request.getParameter("familyeamil");
		System.out.println(familyemail);
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String created_time = dateFormat.format(date);
		Family family = new Family();
		family.setId(UUID.randomUUID().toString());
		family.setFamilyaccount(familyaccount);
		family.setFamilypassword(familypassword);
		family.setFamilyname(familyname);
		family.setCreated_time(created_time);
		family.setFamilyemail(familyemail);
		family.setAddress(request.getParameter("address"));
		System.out.println("-------------"+request.getParameter("address"));
		familyService.registerFamily(family);
		JSONObject result = new JSONObject();
		result.put("result", "success");
		return result.toJSONString();
	}

	// 校验家庭账号
	@ResponseBody
	@RequestMapping("/checkfamilyaccount")
	public String checkFamilyaccount(HttpServletRequest request) {
		String familyaccount = request.getParameter("familyaccount");
		String check = familyService.checkFamilyaccount(familyaccount);
		if (check.equals("exist")) {
			check = "exist";
		} else if (check.equals("empty")) {
			check = "empty";
		}
		JSONObject result = new JSONObject();
	 	result.put("result", check);
		return result.toJSONString();
	}
	/**
	 * 家庭上传头像
	 * @param file
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value="uploadicon",headers="content-type=multipart/*" ,method=RequestMethod.POST)
	public String familyUploadIcon(@RequestParam("file") MultipartFile file) {
	@SuppressWarnings("rawtypes")
	Map map = new HashMap();
	map.put("familyaccount", PrincipalFormat.currentFA());
	try {
	    if (file != null) {
		//if (file.getSize() < 10000) {
		    System.out.println("file is  not null and file size ="+ file.getSize());
		    map.put("familyicon", file.getBytes());
		//}
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	}
	familyService.familyUploadIcon(map);
	JSONObject result = new JSONObject();
	result.put("result", "success");
	return result.toJSONString();
    	}
	
	/**
	 * 上传文件：
	 * 1、保存文件至项目/Tomcat路径下
	 * 2、文件路径保存到数据库中
	 */
	@ResponseBody
	@RequestMapping("/editIcon")
	public String familyEditIcon(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
	    JSONObject result = new JSONObject();
	    if (file.isEmpty()) {
		result.put("result", "文件为空");
		return result.toJSONString();
	    }
	    String fileName = file.getOriginalFilename();
	    log.info("上传文件名为："+fileName);
	    String path = "";
	    //path = ResourceUtils.getFile("familyicon").getAbsolutePath();
	    //path = ResourceUtils.getURL("classpath:").getPath();
	    //path = request.getContextPath();
	    //path = "E://Git//gradesign//gradesign//familyicon//"+fileName;
	    //String filePath = "E://Git//gradesign//gradesign//src//main//resources//static//familyicon//";
	    //String filePath = path.replaceAll("\\", "////");
	    //File dest = new File(path,"/static/familyicon/"+fileName);
	    File folderFile = new File(".\\src\\main\\resources\\static\\familyicon");
	    String iconPath = null;
	    try {
		iconPath = folderFile.getCanonicalPath();
	    } catch (IOException e1) {
		e1.printStackTrace();
	    }
	    String randomPath = UUID.randomUUID().toString();
	    String filePath = iconPath+"\\"+randomPath+fileName;
	    File dest = new File(filePath);
	    log.info("上传路径为："+path);
	    if (!dest.getParentFile().exists()) {
		dest.getParentFile().mkdirs();
	    }
	    try {
		file.transferTo(dest);
		result.put("result", "文件上传成功");
		//将路径保存到数据库
		Map<String, String> map = new HashMap<String, String>();
		map.put("iconurl", "/gradesign/familyicon/"+randomPath+fileName);
		map.put("familyaccount",PrincipalFormat.currentFA());
		familyService.familyEditIcon(map);
		return result.toJSONString();
	    } catch (IllegalStateException e) {
		e.printStackTrace();
	    }catch (IOException e) {
		e.printStackTrace();
	    }
	    
	    result.put("result", "文件上传失败");
	    return result.toJSONString();
	}
	
	/**
	 * 修改用户信息
	 * @param familyname
	 * @param familyemail
	 * @param familyintro
	 * @param familyaccount
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editInfo")
	public String familyEditInfo(@RequestParam String familyname,String familyemail,String familyintro,String familyaccount) {
	    Map<String, String> map = new HashMap<String, String>();
	    map.put("familyname", familyname);
	    map.put("familyemail", familyemail);
	    map.put("familyintro", familyintro);
	    map.put("familyaccount", familyaccount);
	    familyService.familyEditInfo(map);
	    JSONObject result = new JSONObject();
	    result.put("result", "success");
	    return result.toJSONString();
	}
	/**
	 * 忘记密码页面
	 */
	@RequestMapping("forgetPassword")
	public String forgetPassword() {
		return "forgetPassword";
	}
	/**
	 * 发送验证邮件到用户邮箱，并存储验证码到数据库
	 */
	@ResponseBody
	@RequestMapping("/sendEmailValidation")
	public void sendEmailValidation(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String,String>();
		//发送邮件到用户邮箱
		String familyaccount = request.getParameter("familyaccount");
		System.out.println(familyaccount);
		map.put("familyaccount", familyaccount);
		Family family = familyService.getFamilyByAccount(familyaccount);
		//生成验证码
		StringBuffer validationCode = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			validationCode.append((int)((Math.random()*9+1)));
		}
		map.put("validationCode", validationCode.toString());
		EmailHelper.sendEmail(family.getFamilyemail(), "找回密码", "验证码为:"+validationCode);
		//存储验证码到数据库
		familyService.emailValidation(map);
		System.out.println("sendEmailValidation");
	}
	/**
	 * 验证密码后更改用户密码
	 */
	@ResponseBody
	@RequestMapping("/changePwd")
	public String changePwd(HttpServletRequest request) {
		String password = request.getParameter("password");
		String familyaccount = request.getParameter("familyaccount");
		Map<String, String> map = new HashMap<String,String>();
		map.put("password", password);
		map.put("familyaccount", familyaccount);
		familyService.changePwd(map);
		JSONObject object = new JSONObject();
		object.put("result", "success");
		return object.toJSONString();
	}
	/**
	 * 获取用户验证码
	 */
	@ResponseBody
	@RequestMapping("/getValidationCode")
	public String getValidationCode(HttpServletRequest request) {
		String familyaccount = request.getParameter("familyaccount");
		Family family = familyService.getFamilyByAccount(familyaccount);
		String familyemailvalidation = family.getFamilyemailvalidation();
		return familyemailvalidation;
	}
}
